package com.tianye.lc.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.facebook.drawee.view.SimpleDraweeView;
import com.tianye.lc.R;
import com.tianye.lc.common.Final;

import java.util.Iterator;
import java.util.List;

public class YuhuaguRoseDetailActivity extends BaseActivity {
    private TextView show;
    private String name;
    private List<AVObject> keyNameList;
    private LinearLayout images;
    private ImageView likeIcon;
    private JSONObject roseInfo;
    private String roseId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yuhuagu_rose_detail);
        initData();
        initTitle();
        initView();
    }

    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.title_tv);
        name = getIntent().getStringExtra(Final.ROSE_NAME);
        title.setText(name);

        likeIcon = (ImageView) findViewById(R.id.right_iv);
        likeIcon.setVisibility(View.VISIBLE);

        try {
            boolean like = roseInfo.getBoolean("like");
            if (like) {
                likeIcon.setImageResource(R.mipmap.like_icon_yes);
            } else {
                likeIcon.setImageResource(R.mipmap.like_icon_no);
            }
        } catch (Exception e) {
            e.printStackTrace();
            roseInfo.put("like", false);
            likeIcon.setImageResource(R.mipmap.like_icon_no);
        }

        likeIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 第一参数是 className,第二个参数是 objectId
                AVObject todo = AVObject.createWithoutData(Final.BOTANY, roseId);
                boolean like = roseInfo.getBoolean("like");
                if (like) {
                    todo.put("like", false);
                } else {
                    todo.put("like", true);
                }
                // 保存到云端
                todo.saveInBackground(new SaveCallback() {
                    @Override
                    public void done(AVException e) {
                        if (null == e) {
                            boolean like = roseInfo.getBoolean("like");
                            roseInfo.put("like", !like);
                            if (!like) {
                                likeIcon.setImageResource(R.mipmap.like_icon_yes);
                            } else {
                                likeIcon.setImageResource(R.mipmap.like_icon_no);
                            }
                            Toast.makeText(YuhuaguRoseDetailActivity.this, "成功！", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.putExtra("rose_id", roseId);
                            intent.putExtra("like", !like);
                            setResult(RESULT_OK, intent);
                        } else {
                            Toast.makeText(YuhuaguRoseDetailActivity.this, "失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    @Override
    protected int getTitleLayout() {
        return R.layout.title_view_2;
    }

    private void initView() {
        show = (TextView) findViewById(R.id.show);
        images = (LinearLayout) findViewById(R.id.images);
    }

    private void initData() {
        String content = getIntent().getStringExtra(Final.ROSE_INFO);
        roseInfo = JSONObject.parseObject(content);
        roseId = roseInfo.getString("objectId");

        loadKeyNameFromNet();
    }

    private void loadKeyNameFromNet() {
        AVQuery<AVObject> query = new AVQuery<AVObject>(Final.KEY_NAME);
        query.limit(1000);// 最多返回 1000 条结果
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                keyNameList = list;
                show();
            }
        });
    }

    private void show() {
        StringBuffer sb = new StringBuffer();
        try {
            Iterator it = roseInfo.keySet().iterator();
            while (it.hasNext()) {
                String key = (String) it.next();
                String value = roseInfo.getString(key);
                String keyName = getKeyName(key);

                if ("createdAt".equals(key) ||
                        "objectId".equals(key) ||
                        "ACL".equals(key) ||
                        "Botany".equals(value) ||
                        name.equals(value) ||
                        "updatedAt".equals(key)) {
                    continue;
                }
                if ("图片".equals(keyName)) {
                    JSONArray array = JSON.parseArray(value);
                    for (int i = 0; i < array.size(); i++) {
                        addOneImage(array.getJSONObject(i).getString("url"));
                    }
                    continue;
                }
                sb.append(keyName);
                sb.append(value);
                sb.append("\n");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        show.setText(sb.toString());
    }

    private String getKeyName(String key) {
        for (AVObject obj : keyNameList) {
            String objKey = obj.getString("key");
            if (key.equals(objKey)) {
                return obj.getString("desc");
            }
        }
        return "";
    }

    private void addOneImage(String url) {
        SimpleDraweeView simpleDraweeView = new SimpleDraweeView(this);
        int w = getResources().getDimensionPixelSize(R.dimen.rose_detail_image_width);
        LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(w, w);
        llp.bottomMargin = getResources().getDimensionPixelSize(R.dimen.rose_detail_image_margin_bottom);
        simpleDraweeView.setLayoutParams(llp);
        images.addView(simpleDraweeView);

        Uri uri = Uri.parse("http://www.yuhuagu.com" + url);
        simpleDraweeView.setImageURI(uri);
    }
}
